package cn.edu.zafu.bigdata.LiJuan.ch07;

import java.io.Serializable;
import java.io.*;
import java.util.*;

//创建主类
public class StudentInfoSystem{
    private final StudentFileHandler fileHandler = new StudentFileHandler();
    private final List<Student> students;
    public StudentInfoSystem() {
        students = fileHandler.loadStudents();
    }


    //编写用户启动时的方法
    public void start() {
        Scanner scanner = new Scanner(System.in);
        while (true) {

            System.out.println("======= 学生信息管理系统 =======");
            System.out.println("1. 添加学生信息");
            System.out.println("2. 检索学生信息");
            System.out.println("3. 更新学生信息");
            System.out.println("4. 删除学生信息");
            System.out.println("5. 退出程序");
            System.out.print("请输入操作编号 (1-5): ");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1-> addStudent(scanner);
                case 2-> searchStudent(scanner);
                case 3-> updateStudent(scanner);
                case 4-> deleteStudent(scanner);
                case 5->{
                    System.out.println("退出程序...");
                    fileHandler.saveStudents(students);
                    System.exit(0);
                }
                default-> System.out.println("无效的选项，请重新输入。");
            }
        }
    }

    private void addStudent(Scanner scanner) {
        System.out.print("请输入学号: ");
        String id = scanner.nextLine();
        if (students.stream().anyMatch(s -> s.getId().equals(id))) {
            System.out.println("学号重复，请重新输入。");
            return;
        }
        System.out.print("请输入姓名: ");
        String name = scanner.nextLine();
        System.out.print("请输入电话: ");
        String phone = scanner.nextLine();
        Student student = new Student(id, name, phone);
        students.add(student);
        System.out.println("学生信息添加成功。");
    }

    private void searchStudent(Scanner scanner) {
        System.out.print("请输入学号进行检索: ");
        String id = scanner.nextLine();
        Optional<Student> studentOptional = students.stream().filter(s -> s.getId().equals(id)).findFirst();
        if (studentOptional.isPresent()) {
            System.out.println("找到学生信息：" + studentOptional.get());
        } else {
            System.out.println("未找到该学生。");
        }
        System.out.print("继续检索？输入 'QUIT' 退出: ");
        if (!scanner.nextLine().equalsIgnoreCase("QUIT")) {
            searchStudent(scanner);
        }
    }

    private void updateStudent(Scanner scanner) {
        System.out.print("请输入学号进行更新: ");
        String id = scanner.nextLine();
        Optional<Student> studentOptional = students.stream().filter(s -> s.getId().equals(id)).findFirst();
        if (studentOptional.isPresent()) {
            Student student; //= studentOptional.get();
            System.out.print("请输入新姓名: ");
            String name = scanner.nextLine();
            System.out.print("请输入新电话: ");
            String phone = scanner.nextLine();
            student = new Student(id, name, phone);
            int index = students.indexOf(studentOptional.get());
            students.set(index, student);
            System.out.println("学生信息更新成功。");
        } else {
            System.out.println("未找到该学生。");
        }
        System.out.print("继续更新？输入 'QUIT' 退出: ");
        if (!scanner.nextLine().equalsIgnoreCase("QUIT")) {
            updateStudent(scanner);
        }
    }

    private void deleteStudent(Scanner scanner) {
        System.out.print("请输入学号进行删除: ");
        String id = scanner.nextLine();
        Iterator<Student> iterator = students.iterator();
        while (iterator.hasNext()) {
            Student student = iterator.next();
            if (student.getId().equals(id)) {
                iterator.remove();
                System.out.println("学生信息删除成功。");
                return;
            }
        }
        System.out.println("未找到该学生。");
        System.out.print("继续删除？输入 'QUIT' 退出: ");
        if (!scanner.nextLine().equalsIgnoreCase("QUIT")) {
            deleteStudent(scanner);
        }
    }
    //主程序入口
    public static void main(String[] args) {
        new StudentInfoSystem().start();
    }
}
//创建学生类
class Student implements Serializable{
    //定义变量
    @Serial
    private static final long serialVersionUID = 1L;
    private final String id;
    private final String name;
    private final String phone;
    //构造函数
    public Student(String id, String name, String phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getPhone() {
        return phone;
    }
    //重写toString(),有返回值
    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }

}
//序列化和反序列化学生信息
class StudentFileHandler{
    private static final String FILENAME = "files/students.ser11080105";

    // 辅助方法，用于确保文件所在的目录存在
    private void ensureDirectoryExists() {
        File directory = new File(FILENAME).getParentFile();
        if (directory != null && !directory.exists()) {
            directory.mkdirs(); // 创建目录
        }
    }

    public void saveStudents(List<Student> students) {
        ensureDirectoryExists(); // 确保目录存在
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILENAME))) {
            oos.writeObject(students);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<Student> loadStudents() {
        List<Student> students = new ArrayList<>();
        File file = new File(FILENAME);
        if (file.exists() && file.length() > 0) {
            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILENAME))) {
                students = (List<Student>) ois.readObject();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
                // 如果读取失败，创建一个新的空列表并保存
                saveStudents(new ArrayList<>());
                students = new ArrayList<>();
            }
        } else {
            // 如果文件不存在或为空，创建一个新的空列表并保存
            saveStudents(new ArrayList<>());
        }
        return students;
    }
}
